package com.core.website.service.impl;

import cn.easyes.core.biz.PageInfo;
import com.core.website.entity.*;
import com.core.website.mapper.ColumnMapper;
import com.core.website.mapper.ContentMapper;
import com.core.website.mapper.OrganizationMapper;
import com.core.website.mapper.UserMapper;
import com.core.website.service.ContentService;
import com.core.website.util.CopyUtils;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private ColumnMapper columnMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EsServiceImpl esService;
    public static final String approvalSuccess="1";
    public static final String approvalFail="-1";
    @Override
    @CacheEvict(value="content",allEntries = true)
    public int add(Content content) {
        content.setId(UUID.randomUUID().toString().toUpperCase().replace("-", ""));
        if(! "1".equals(content.getApproval())){
            content.setApproval("0");
        }
        if(StringUtils.isEmpty(content.getTopContent())){
            content.setTopContent("0");
        }
        if(StringUtils.isEmpty(content.getNiceContent())){
            content.setNiceContent("0");
        }
        // 处理一下 no
        if(content.getNo()==null){
            content.setNo("");
        }
//        esService.insert(content);
        if(!StringUtils.isEmpty(content.getSignBy())){
            int add = contentMapper.add(content);
            contentMapper.approval(content.getId(),"1","","1","admin");
            Content result = contentMapper.queryById(content.getId());
            if(null!=result){
                esService.insert(result);
            }
            return add;
        }else{
            return contentMapper.add(content);
        }
    }
    @Override
    @CacheEvict(value="content",allEntries = true)
    public int approval(Approval approval) {
        String newContent=null;
        if("1".equals(approval.getApprovalResult())){
            newContent="1";
        }
        User subject = (User) SecurityUtils.getSubject().getPrincipal();
        if("admin".equals(subject.getUserName())){
            contentMapper.approval(approval.getContentId(),approval.getApprovalResult(),approval.getApprovalReason(),newContent,subject.getUserName());
        }else{
            contentMapper.approval(approval.getContentId(),approval.getApprovalResult(),approval.getApprovalReason(),newContent,subject.getId());
        }
        if(approvalSuccess.equals(approval.getApprovalResult())){
            Content content = contentMapper.queryById(approval.getContentId());
            if(null!=content){
                esService.insert(content);
            }
        }
//        esService.insert(content);
//        return contentMapper.add(content);
        return 1;
    }

    @Override
    @CacheEvict(value="content",allEntries = true)
    public int edit(Content content) {
        // 处理一下 no
        if(content.getNo()==null){
            content.setNo("");
        }
        int edit = contentMapper.edit(content);
        if(edit>0){
            Content content1 = contentMapper.queryById(content.getId());
            if(approvalSuccess.equals(content1.getApproval())){
                esService.deleteById(content1.getId());
            }
        }
        return edit;
    }
    @Override
    @CacheEvict(value="content",allEntries = true)
    public int changeNo(Content content) {
        // 处理一下 no
        if(content.getNo()==null){
            content.setNo("");
        }
        int edit = contentMapper.changeNo(content);
        if(edit>0){
            Content content1 = contentMapper.queryById(content.getId());
            if(approvalSuccess.equals(content1.getApproval())){
                esService.updateById(content1);
            }
        }
        return edit;
    }
    @Override
    @CacheEvict(value="content",allEntries = true)
    public int unNew(List<String> list) {
        int edit = contentMapper.unNew(list);
        for(String id:list){
            Content content1 = contentMapper.queryById(id);
            if(approvalSuccess.equals(content1.getApproval())){
                try {
                    esService.updateById(content1);
                }catch (Exception e){

                }

            }
        }
        return edit;
    }

    @Override
    @CacheEvict(value="content",allEntries = true)
    public int delete(List<String> ids) {
        for(String id:ids){
            esService.deleteById(id);
        }
        return contentMapper.delete(ids);
    }

    @Override
    @Cacheable(value = "content",keyGenerator = "selfKeyGenerate")
    public List<Content> queryAll(Content content) {
        List<Content> result=new ArrayList<>();
        if(!StringUtils.isEmpty(content.getOrganization())){ // 机构上传的新闻
            String columnId = content.getColumnId();
            Column column = new Column();
            column.setParentId(columnId);
            List<Column> columns = columnMapper.queryAll(column);

            if(columns.size()>0){ // 存在子栏目 需要重新设置一下顺序了
                /*for(Column column1:columns){
                    Content copy = CopyUtils.copy(content, Content.class);
                    copy.setColumnId(column1.getId());
                    if(null!=content.getPageNum()&&content.getPageNum()>0&&null!=content.getPageSize()&&content.getPageSize()>0){
                        PageHelper.startPage(content.getPageNum(), content.getPageSize());
                    }
                    List<Content> contents = contentMapper.queryAll(copy);
                    result.addAll(contents);

                }*/
                Content copy = CopyUtils.copy(content, Content.class);
                copy.setParentId(content.getColumnId()); //设置父id的值
                copy.setColumnId(null); // 栏目id设置为null 因为查询父亲 就带子了
                result = contentMapper.queryAll(copy);
            }else{
                result=contentMapper.queryAll(content);
            }
        }else{ // 网站访问数据
            if(null!=content.getPageNum()&&content.getPageNum()>0&&null!=content.getPageSize()&&content.getPageSize()>0){
                PageHelper.startPage(content.getPageNum(), content.getPageSize());
            }
            result=contentMapper.queryAll(content);
        }

        return result;
    }
    @Override
    @Cacheable(value = "content",keyGenerator = "selfKeyGenerate")
    public List<Content> queryFourData(Content content) {
        List<Content> result=new ArrayList<>();
        if(!StringUtils.isEmpty(content.getOrganization())){ // 机构上传的新闻
            String columnId = content.getColumnId();
            Column column = new Column();
            column.setParentId(columnId);
            List<Column> columns = columnMapper.queryAll(column);

            if(columns.size()>0){
                for(Column column1:columns){
                    Content copy = CopyUtils.copy(content, Content.class);
                    copy.setColumnId(column1.getId());
                    if(null!=content.getPageNum()&&content.getPageNum()>0&&null!=content.getPageSize()&&content.getPageSize()>0){
                        PageHelper.startPage(content.getPageNum(), content.getPageSize());
                    }
                    List<Content> contents = contentMapper.queryFourData(copy);
                    result.addAll(contents);

                }
            }else{
                result=contentMapper.queryFourData(content);
            }
        }else{ // 网站访问数据
            if(null!=content.getPageNum()&&content.getPageNum()>0&&null!=content.getPageSize()&&content.getPageSize()>0){
                PageHelper.startPage(content.getPageNum(), content.getPageSize());
            }
            result=contentMapper.queryFourData(content);
        }

        return result;
    }
    @Override
    @Cacheable(value = "approvalContent",keyGenerator = "selfKeyGenerate")
    public List<Content> queryApprovalPage(Content content) {
        List<Content> result=new ArrayList<>();
        List<String> columnIdList=null;
        if(!StringUtils.isEmpty(content.getCreateBy())){
            User user = userMapper.findById(content.getCreateBy());
            if(null!=user&&!StringUtils.isEmpty(user.getOrganizationId())){
                columnIdList = contentMapper.getApprovalAuthByOrgId(user.getOrganizationId());
                if(null==columnIdList||columnIdList.size()==0){
                    return new ArrayList<>();
                }
            }
        }
        if(!StringUtils.isEmpty(content.getCreateBy())){ // 管理员查询所有栏目
            String columnId = content.getColumnId();
            Column column = new Column();
            column.setParentId(columnId);
            List<Column> columns = columnMapper.queryAll(column);

            if(columns.size()>0){
                for(Column column1:columns){
                    Content copy = CopyUtils.copy(content, Content.class);
                    copy.setColumnId(column1.getId());
                    if(null!=content.getPageNum()&&content.getPageNum()>0&&null!=content.getPageSize()&&content.getPageSize()>0){
                        PageHelper.startPage(content.getPageNum(), content.getPageSize());
                    }
                    List<Content> contents = contentMapper.queryApprovalPage(copy,columnIdList);
                    result.addAll(contents);

                }
            }else{
                result=contentMapper.queryApprovalPage(content,columnIdList);
            }
        }else{
            if(null!=content.getPageNum()&&content.getPageNum()>0&&null!=content.getPageSize()&&content.getPageSize()>0){
                PageHelper.startPage(content.getPageNum(), content.getPageSize());
            }
            result=contentMapper.queryApprovalPage(content,columnIdList);
        }

        return result;
    }
    @Override
    public PageInfo<Content> globalQueryAll(Content content) {
//        content.setApproval("1");
        return esService.search(content);
    }
    @Override
    public PageInfo<Content> globalQueryAllContent(Content param) {
        return esService.globalQueryAllContent(param);
    }
    @Override
    @Cacheable(value = "content",keyGenerator = "selfKeyGenerate")
    public List<Content> queryCascadeAll(Content content) {
        return contentMapper.queryCascadeAll(content);
    }

    @Override
    @Cacheable(value = "content",key = "#id")
    public Content queryOne(String id) {

        return contentMapper.queryById(id);
    }

    @Override
    @CacheEvict(value="content",allEntries = true)
    public int top(String id,String type) {
        return contentMapper.top(id,type);
    }
    @Override
    @CacheEvict(value="content",allEntries = true)
    public int nice(String id,String type) {
        return contentMapper.nice(id,type);
    }

    @Override
    @Cacheable(value = "content",key = "#id.concat(#columnId)")
    public Map<String,Content> turnPages(String id,String columnId) {
        Content query = new Content();
        query.setColumnId(columnId);
        query.setApproval(approvalSuccess);
        List<Content> contents = contentMapper.queryAll(query);
        Map<String,Content> result=new HashMap<>();
        result.put("previous",null);
        result.put("next",null);
        Content previous=null;
        Content next=null;
        if(contents.size()>0){
            for(int i=0;i<contents.size();i++){
                if(contents.get(i).getId().equals(id)){
                    if(i>0){
                        previous=contents.get(i-1);
                        result.put("previous",previous);
                    }
                    if(i!=contents.size()-1){
                        next=contents.get(i+1);
                        result.put("next",next);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> statistics(String yearAndMonth) {
        List<Map<String,Object>> result=new ArrayList<>();
        List<Organization> organizations=organizationMapper.queryAll(new Organization());
        //先查询机构
        //统计本月各个机构的文章发布数量
        //循环每个机构，找到map中对应的key并赋予对应的数量
        List<Content> statistics = esService.statistics(yearAndMonth);
        HashMap<String, List<Content>> stringListHashMap=new HashMap<>();
        if(!CollectionUtils.isEmpty(statistics)){
            stringListHashMap = (HashMap<String, List<Content>>) statistics.stream().collect(Collectors.groupingBy(x -> x.getOrganization()));
        }
        for(Organization organization:organizations){
            if(StringUtils.isEmpty(organization.getParentId())||"0".equals(organization.getStatistic())){
                continue;
            }
            int size=0;
            if(stringListHashMap.keySet().contains(organization.getId())){
                size = stringListHashMap.get(organization.getId()).size();
            }
            Map<String,Object> map=new HashMap();
            map.put("id",organization.getId());
            map.put("name",organization.getName());
            map.put("size",size);
            result.add(map);
        }
//        if(result.size()>0){
//            List<Map<String, Object>> collect = result.stream().sorted(Comparator.comparing(ContentServiceImpl::comparingBySize).reversed())
//                    .collect(Collectors.toList());
//            return collect;
//        }
        return result;
    }
    public static int comparingBySize(Map<String, Object> map){
        return Integer.parseInt(map.get("size").toString());
    }
    @Override
    public List<Map<String, Object>> queryCascadeContentGroupByColumnId(String id) {
        List<String> idList=new ArrayList<>();
        idList.add(id);
        Column column=new Column();
        column.setParentId(id);
        List<Column> columns = columnMapper.queryAll(column);
        List<Organization> organizations=organizationMapper.queryAll(new Organization());
        if(null!=columns&&columns.size()>0){
            //有下级
            for(Column column1:columns){
                idList.add(column1.getId());
            }
        }
        List<Map<String,Object>> result=new ArrayList<>();
        if(null!=organizations&&organizations.size()>0){
            for(Organization organization:organizations){
                if(!organization.getStatistic().equals("1")){
                    continue;
                }
                List<Content> list=contentMapper.queryCascadeContentGroupByColumnId(idList,organization.getId());
                if(null!=list&&list.size()>0){
                    Map<String,Object> map=new HashMap<>();
                    map.put("orgId",organization.getId());
                    map.put("orgName",organization.getName());
                    map.put("contentList",list);
                    result.add(map);
                }
            }
        }
        return result;
    }
    @Override
    public List<Map<String, Object>> queryGroupByOrg(String id) {
        List<String> idList=new ArrayList<>();
        idList.add(id);
        Column column=new Column();
        column.setParentId(id);
        List<Column> columns = columnMapper.queryAll(column);
        List<Map<String,Object>> result=new ArrayList<>();
        List<Organization> organizations=organizationMapper.queryAll(new Organization());

        if(null!=columns&&columns.size()>0){
            //有下级
            for(Column column1:columns){
                idList.add(column1.getId());
            }
            if(null!=organizations&&organizations.size()>0){
                for(Organization organization:organizations){
                    List<Content> list=contentMapper.queryCascadeContentGroupByColumnId(idList,organization.getId());
                    if(null!=list&&list.size()>0){
                        Map<String,Object> map=new HashMap<>();
                        map.put("orgId",organization.getId());
                        map.put("orgName",organization.getName());
                        map.put("contentList",list);
                        result.add(map);
                    }
                }
            }
        }else{
            if(null!=organizations&&organizations.size()>0){
                for(Organization organization:organizations){
                    List<Content> list=contentMapper.queryGroupByOrg(id,organization.getId());
                    if(null!=list&&list.size()>0){
                        Map<String,Object> map=new HashMap<>();
                        map.put("orgId",organization.getId());
                        map.put("orgName",organization.getName());
                        map.put("contentList",list);
                        result.add(map);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public int queryThumbs(String ip, String id) {
        return contentMapper.queryThumbs(ip,id);
    }

    @Override
    public void addThumbs(String ip, String id) {
        contentMapper.addThumbs(ip,id);
    }

    @Override
    public List<Map<String, Object>> statistics1(String year) {
        List<Organization> organizations=organizationMapper.queryAll(new Organization());
        // 查询所有新闻包括未通过的稿件
        List<Map<String, Object>> mapList = contentMapper.statistics1(year);
        Map<String, List<Map<String, Object>>> organizationMap=new HashMap<>();
        if(mapList.size()>0){
            organizationMap = mapList.stream().collect(Collectors.groupingBy(x -> x.get("id").toString()));
        }
        List<Map<String,Object>> result=new ArrayList<>();
        for (Organization organization : organizations) {
            if (!"1".equals(organization.getStatistic())||StringUtils.isEmpty(organization.getParentId())) {
                continue;
            }
            Map m = new HashMap();
            m.put("name", organization.getName());
            m.put("num", null == organizationMap.get(organization.getId()) ? 0 : organizationMap.get(organization.getId()).get(0).get("num"));
            result.add(m);
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> statistics2(String year) {
        List<Organization> organizations=organizationMapper.queryAll(new Organization());
        // 查询已通过的新闻
        List<Map<String, Object>> mapList = contentMapper.statistics2(year);
        Map<String, List<Map<String, Object>>> organizationMap=new HashMap<>();
        if(mapList.size()>0){
            organizationMap = mapList.stream().collect(Collectors.groupingBy(x -> x.get("id").toString()));
        }
        List<Map<String,Object>> result=new ArrayList<>();
        for(Organization organization:organizations){
            if (!"1".equals(organization.getStatistic())||StringUtils.isEmpty(organization.getParentId())) {
                continue;
            }
            Map m=new HashMap();
            m.put("name",organization.getName());
            m.put("num",null==organizationMap.get(organization.getId())?0:organizationMap.get(organization.getId()).get(0).get("num"));
            result.add(m);
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> statistics3(String year) {
        List<Organization> organizations=organizationMapper.queryAll(new Organization());
        List<Map<String, Object>> map1 = contentMapper.statistics1(year);
        List<Map<String, Object>> map2 = contentMapper.statistics2(year);
        Map<String, List<Map<String, Object>>> organizationMap1=new HashMap<>();
        if(map1.size()>0){
            organizationMap1 = map1.stream().collect(Collectors.groupingBy(x -> x.get("id").toString()));
        }
        Map<String, List<Map<String, Object>>> organizationMap2=new HashMap<>();
        if(map2.size()>0){
            organizationMap2 = map2.stream().collect(Collectors.groupingBy(x -> x.get("id").toString()));
        }
        List<Map<String,Object>> result=new ArrayList<>();

        NumberFormat percent = NumberFormat.getPercentInstance();
        percent.setMaximumFractionDigits(2);
        for(Organization organization:organizations){
            if (!"1".equals(organization.getStatistic())||StringUtils.isEmpty(organization.getParentId())) {
                continue;
            }
            Map m=new HashMap();
            m.put("name",organization.getName());
            int total=null==organizationMap1.get(organization.getId())?0:Integer.parseInt(organizationMap1.get(organization.getId()).get(0).get("num").toString());
            int pass=null==organizationMap2.get(organization.getId())?0:Integer.parseInt(organizationMap2.get(organization.getId()).get(0).get("num").toString());
            if(0==total){
                m.put("num",0);
            }else{
                BigDecimal a1=BigDecimal.valueOf(total);
                BigDecimal a2=BigDecimal.valueOf(pass);
                BigDecimal r = a2.divide(a1,3,BigDecimal.ROUND_HALF_UP);
                m.put("num",percent.format(r.doubleValue()));
            }
            result.add(m);
        }
        return result;
    }
    @Override
    public List<Map<String, Object>> statistics5(String year) {//投稿达人榜
        List<Map<String, Object>> result = contentMapper.statistics5(year);
//        List<Organization> organizations=organizationMapper.queryAll(new Organization());
//        List<Map<String, Object>> map1 = contentMapper.statistics1(year);
//        List<Map<String, Object>> map2 = contentMapper.statistics2(year);
//        Map<String, List<Map<String, Object>>> organizationMap1=new HashMap<>();
//        if(map1.size()>0){
//            organizationMap1 = map1.stream().collect(Collectors.groupingBy(x -> x.get("id").toString()));
//        }
//        Map<String, List<Map<String, Object>>> organizationMap2=new HashMap<>();
//        if(map2.size()>0){
//            organizationMap2 = map2.stream().collect(Collectors.groupingBy(x -> x.get("id").toString()));
//        }
//        List<Map<String,Object>> result=new ArrayList<>();
//
//        NumberFormat percent = NumberFormat.getPercentInstance();
//        percent.setMaximumFractionDigits(2);
//        for(Organization organization:organizations){
//            if (!"1".equals(organization.getStatistic())||StringUtils.isEmpty(organization.getParentId())) {
//                continue;
//            }
//            Map m=new HashMap();
//            m.put("name",organization.getName());
//            int total=null==organizationMap1.get(organization.getId())?0:Integer.parseInt(organizationMap1.get(organization.getId()).get(0).get("num").toString());
//            int pass=null==organizationMap2.get(organization.getId())?0:Integer.parseInt(organizationMap2.get(organization.getId()).get(0).get("num").toString());
//            if(0==total){
//                m.put("num",0);
//            }else{
//                BigDecimal a1=BigDecimal.valueOf(total);
//                BigDecimal a2=BigDecimal.valueOf(pass);
//                BigDecimal r = a2.divide(a1,3,BigDecimal.ROUND_HALF_UP);
//                m.put("num",percent.format(r.doubleValue()));
//            }
//            result.add(m);
//        }S
        return result;
    }
    @Override
    public List<Map<String, Object>> mainBanner() {
        List<Map<String, Object>> result = contentMapper.mainBanner();
        if(result.size()>0){
            for(Map<String,Object> map:result){
                String string = map.get("content").toString();
                int src = string.indexOf("src");
                String substring = string.substring(src+5, string.length());
                int i = substring.indexOf("\"");
                String substring1 = substring.substring(0, i);
                System.out.println(substring1);
                map.put("src",substring1);
                map.remove("content");
            }
        }
        return result;
    }

    @Override
    public List<String> getApprovalAuthByOrgId(String orgId) {
        return contentMapper.getApprovalAuthByOrgId(orgId);
    }

    @Override
    public void saveApprovalAuthByOrgId(String orgId, List<String> columnIdList) {
        contentMapper.deleteApprovalAuthByOrgId(orgId);
        List<Column>  columnList = columnMapper.selectChildColumnList(columnIdList);
        List<Map> list = new ArrayList<>();
        for(Column c:columnList){
            // 构建栏目对象
            Map<String,String> map = new HashMap<>();
            map.put("orgId",orgId); // 机构id
            map.put("id",c.getId()); // 栏目id
            list.add(map);
        }
        // 批量添加
        contentMapper.batchSaveApprovalAuthByOrgId(list);
       /* for(String id:columnIdList){
            contentMapper.saveApprovalAuthByOrgId(orgId,id);
        }*/
    }

    @Override
    public List<Content> queryTransferApprovalPage(Content content) {
        List<Content> result = null;
        result=contentMapper.queryTransferApprovalPage(content);
        return result;
    }

    @Override
    public List<Content> queryListByOrg(Content content) {
        List<Content> result = null;
        if(!StringUtils.isEmpty(content.getOrganization())){ // 机构上传的新闻
            String columnId = content.getColumnId();
            Column column = new Column();
            column.setParentId(columnId);
            List<Column> columns = columnMapper.queryAll(column);

            if(columns.size()>0){ // 存在子栏目 需要重新设置一下顺序了
                Content copy = CopyUtils.copy(content, Content.class);
                copy.setParentId(content.getColumnId()); //设置父id的值
                copy.setColumnId(null); // 栏目id设置为null 因为查询父亲 就带子了
                result = contentMapper.queryListByOrg(copy);
            }else{
                result=contentMapper.queryListByOrg(content);
            }
        }else{ // 网站访问数据
            if(null!=content.getPageNum()&&content.getPageNum()>0&&null!=content.getPageSize()&&content.getPageSize()>0){
                PageHelper.startPage(content.getPageNum(), content.getPageSize());
            }
            result=contentMapper.queryListByOrg(content);
        }

        return result;
    }
}